<template>
  <el-dialog
    title="选择用户"
    :visible.sync="visible"
    width="1200px"
    top="5vh"
    append-to-body
    @close="handleClose"
  >
    <el-row :gutter="20">
      <!-- 左侧部门树 -->
      <el-col :span="6">
        <el-card shadow="hover" style="height: 100%">
          <el-input
            placeholder="请输入部门名称"
            v-model="deptName"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
          <el-scrollbar style="height: 480px">
            <el-tree
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              default-expand-all
              highlight-current
              @node-click="handleNodeClick"
            />
          </el-scrollbar>
        </el-card>
      </el-col>

      <!-- 右侧用户列表 -->
      <el-col :span="18">
        <!-- 搜索表单 -->
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
        >
          <el-form-item label="账号名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
            <el-button type="primary" size="mini" @click="handleSelectUser"
              >确 定</el-button
            >
          </el-form-item>
        </el-form>

        <!-- 用户列表 -->
        <el-table
          v-loading="loading"
          ref="table"
          :data="userList"
          @selection-change="handleSelectionChange"
          @row-click="clickRow"
          :row-style="{ height: '35px' }"
          :cell-style="{ padding: '0px' }"
          height="395px"
          :class="{ 'no-multiple': !isMultiple }"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            type="index"
            :index="indexMethod"
            width="60"
          />
          <el-table-column
            label="账号名称"
            prop="userName"
            :show-overflow-tooltip="true"
            align="center"
            width="200"
          />
          <el-table-column
            label="用户姓名"
            prop="nickName"
            :show-overflow-tooltip="true"
            align="center"
            width="150"
          />
          <el-table-column
            label="职位"
            prop="position"
            :show-overflow-tooltip="true"
            align="center"
            width="80"
          />
          <el-table-column
            label="手机"
            prop="phonenumber"
            :show-overflow-tooltip="true"
            align="center"
            width="120"
          />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="150"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
import { listUser, listByOrgId, deptTreeSelect } from "@/api/system/user";
import { unallocatedUserList, roleMenuList } from "@/api/system/role";

export default {
  name: "SelectUserInfo",
  dicts: ["sys_normal_disable"],
  props: {
    // 角色编号
    roleId: {
      type: [Number, String],
      default: "",
    },
    menuId: {
      type: [Number, String],
      default: "",
    },
    sign: {
      type: [Number, String],
      default: "",
    },
    // 0多选 1单选
    type: {
      type: [Number, String],
      default: "0",
    },
    // 是否是问卷或者活动选择本公司的用户
    isActOrQues: {
      type: Number,
      default: 0,
    },
    // 已选用户数据
    selectedData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示状态
      visible: false,
      // 部门名称
      deptName: "",
      // 部门树选项
      deptOptions: undefined,
      // 树形配置
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 选中数组值
      userIds: [],
      nickNames: [],
      phones: [],
      positions: [],
      // 单选时使用的临时变量
      userId: "",
      nickName: "",
      phone: "",
      position: "",
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 是否多选模式
      isMultiple: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        deptId: undefined,
        userName: undefined,
        phonenumber: undefined,
      },
      // 选中的行数据
      selectionList: [],
    };
  },
  watch: {
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getDeptTree();
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.toLowerCase().indexOf(value.toLowerCase()) !== -1;
    },

    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },

    // 显示弹框
    show() {
      this.visible = true;
      this.reset();
      this.getList();
    },

    // 关闭弹框
    handleClose() {
      this.reset();
    },

    // 重置数据
    reset() {
      this.loading = false;
      this.userIds = [];
      this.nickNames = [];
      this.phones = [];
      this.positions = [];
      this.userId = "";
      this.nickName = "";
      this.phone = "";
      this.position = "";
      this.selectionList = [];
      this.queryParams.pageNum = 1;
      this.queryParams.deptId = undefined;
      this.queryParams.userName = undefined;
      this.queryParams.phonenumber = undefined;

      if (this.$refs.table) {
        this.$refs.table.clearSelection();
      }
    },

    // 序号展示
    indexMethod(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },

    // 行点击事件
    clickRow(row) {
      this.$refs.table.toggleRowSelection(row);
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectionList = selection;

      if (selection.length === 0) {
        this.userIds = [];
        this.nickNames = [];
        this.phones = [];
        this.positions = [];
      } else {
        if (this.type === "1") {
          // 单选
          if (selection.length > 1) {
            const lastSelected = selection[selection.length - 1];
            this.$refs.table.clearSelection();
            this.$refs.table.toggleRowSelection(lastSelected, true);
            selection = [lastSelected];
          }
          // 单选数据
          this.userId = selection[0].userId;
          this.nickName = selection[0].nickName;
          this.phone = selection[0].phonenumber;
          this.position = selection[0].position;
        } else {
          // 多选
          // 收集所有选中用户的数据
          this.userIds = selection.map(item => item.userId);
          this.nickNames = selection.map(item => item.nickName);
          this.phones = selection.map(item => item.phonenumber);
          this.positions = selection.map(item => item.position);
        }
      }
    },

    // 设置已选行的选中状态
    setSelectedRows() {
      if (this.selectedData && this.selectedData.length > 0) {
        this.$nextTick(() => {
          if (this.userList && this.userList.length > 0) {
            this.$refs.table.clearSelection();
            this.userList.forEach(row => {
              const isSelected = this.selectedData.some(
                selected => String(selected.userId) === String(row.userId)
              );
              if (isSelected) {
                this.$refs.table.toggleRowSelection(row, true);
              }
            });
          }
        });
      }
    },

    /** 查询用户列表 */
    getList() {
      this.loading = true;
      if (this.type === "1") {
        this.isMultiple = false;
      }

      const request =
        this.sign === "1"
          ? listUser(this.queryParams)
          : this.sign === "2"
          ? roleMenuList({ ...this.queryParams, menuId: this.menuId })
          : unallocatedUserList(this.queryParams);

      request
        .then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.setSelectedRows();
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.handleQuery();
    },

    /** 确定按钮操作 */
    handleSelectUser() {
      if (this.type === "0") {
        // 多选
        if (!this.selectionList.length) {
          this.$modal.msgError("请选择要分配的用户");
          return;
        }
        this.visible = false;
        this.$emit(
          "ok",
          this.userIds,
          this.nickNames,
          this.phones,
          this.positions
        );
      } else if (this.type === "1") {
        // 单选
        if (!this.selectionList.length) {
          this.$modal.msgError("请选择用户");
          return;
        }
        this.visible = false;
        this.$emit("ok", this.userId, this.nickName, this.phone, this.position);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.no-multiple {
  ::v-deep .el-table__header-wrapper .el-checkbox {
    display: none;
  }
}

.el-dialog {
  .el-scrollbar {
    .el-scrollbar__wrap {
      margin-bottom: 0 !important;
    }
  }
}
</style>
